package com.example.demo.controller;

import com.example.demo.mapper.UserMapper;
import com.example.demo.model.User;
import com.example.demo.tools.Constant;
import com.example.demo.tools.ResponseBody;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * Creat with IntelliJ IDEA
 * Description:
 * User:WZW
 * Date:2022-08-30
 * Time:21:35
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @RequestMapping("/login")
    public ResponseBody<User> login(@RequestParam String username,
                                    @RequestParam String password,
                                    HttpServletRequest request) {

        User user = userMapper.selectByName(username);

        if (user != null) {
            boolean flg = bCryptPasswordEncoder.matches(password,user.getPassword());
            if (!flg) {
                return new ResponseBody<>(-1,"用户名或者密码错误！",user);
            }
            request.getSession().setAttribute(Constant.USERINFO_SESSION_KEY,user);
            return new ResponseBody<>(0, "登录成功！",user);
        } else {
            System.out.println("登录失败！");
            return new ResponseBody<>(-1, "用户名或者密码错误",user);
        }
    }

//    @RequestMapping("/login")
//    public ResponseBody<User> login(@RequestParam String username,
//                                    @RequestParam String password,
//                                    HttpServletRequest request) {
//        User userLogin = new User();
//        userLogin.setUsername(username);
//        userLogin.setPassword(password);
//
//        User user = userMapper.login(userLogin);
//
//        if (user != null) {
//            System.out.println("登录成功！");
//            request.getSession().setAttribute(Constant.USERINFO_SESSION_KEY,user);
//            return new ResponseBody<>(0, "登录成功！",userLogin);
//        } else {
//            System.out.println("登录失败！");
//            return new ResponseBody<>(-1, "登录失败！",userLogin);
//        }
//    }

}
